<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VueStudyDemo</title>
</head>
<body>
<div id="app">
    <div><a href="index.html">返回首页</a></div><hr>
    <button @click = "clickMe">commit a mutations</button>
    <button @click = "clickByPayLoad">commit a payLoad 10 mutations </button>
    <button @click = "clickObjectStyleCommit">commit a payLoad amount:10 mutations by object-style </button>
    <button @click = "plusBarByObjectPayLoad({amount:100})">mapMutations</button>
    <div>{{bar}}</div>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<script>
    // 常量化 mutation 的 type
    // 这样做的好处是，可以配置工具调试，同时也可以使得团队一眼就能知悉所有的mutations
    const PLUS_BAR = 'plusBar'

    // 实例化store
    const store = new Vuex.Store({
        state: {
            bar: 1
        },
        mutations: {
            // each mutation has a string [type] and a [handler]:
            // plusBar: <string> [type] | [handler]
            // []中括号是ES6的一个新增特性：计算一个值并作为一个属性名称或变量名称 ： ES2015 computed property name feature
            [PLUS_BAR](state) {
                state.bar++
            },
            // n 就是 payload, 意思为装载，装弹
            plusBarBySimplePayLoad(state, n) {
                state.bar += n
            },
            // In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive:
            plusBarByObjectPayLoad(state, payload) {
                state.bar += payload.amount
            }
        }

    })

    new Vue({
        el: '#app',
        //store
        store,
        // state
        data () {
            return {}
        },
        computed: {
            // Vuex的amp系统方法解构赋值，等于将store中的状态'bar'赋给当前实例的一个computed属性'bar'
            ...Vuex.mapState(['bar'])
        },
        // actions
        methods: {
            clickMe() {
                // 任何时候切记，不要直接在子组件中改变state，正确的操作是通过store.commit('mutationsTypeName')来间接改变状态值
                this.$store.commit('plusBar')
            },
            clickByPayLoad() {
                // 使用了payload的mutation
                this.$store.commit('plusBarByObjectPayLoad', { amount: 10 })
            },
            clickObjectStyleCommit() {
                // 使用对象参数风格来commit一个mutation
                this.$store.commit({type:'plusBarByObjectPayLoad',amount: 15})
            },
            // 利用辅助函数，直接将mutations解构成自身的方法，效果同store.commit
            ...Vuex.mapMutations(['plusBarByObjectPayLoad'])
        }
    })
    // 结语：store.mutations只能做同步变异。如果要异步变异，请使用store.actions
</script>
</body>
</html>